﻿using System;
using System.Collections.Generic;
using System.IO;
using NPOI.HSSF.UserModel;

namespace PhoobearLibs.Resource.Resx
{
    public class XlsFile : ResourceFile<string>
    {

#region Public Property

        /// <summary>
        /// 데이터가 시작되는 row
        /// </summary>
        private int _startRow = 1;
        public int StartRow
        {
            get
            {
                return _startRow;
            }

            private set
            {
                _startRow = value > 0 ? value : 0;
            }
        }

        /// <summary>
        /// 해당 데이터가 있는 Sheet
        /// </summary>
        private int _sheetNo = 0;
        public int SheetNo
        {
            get
            {
                return _sheetNo;
            }

            private set
            {
                _sheetNo = value > 0 ? value : 0;
            }
        }

        /// <summary>
        /// ID 목록의 column
        /// </summary>
        private int _idColumn = 0;
        public int IdColumn
        {
            get
            {
                return _idColumn;
            }

            private set
            {
                _idColumn = value > 0 ? value : 0;
            }
        }

        /// <summary>
        /// Value 목록의 column
        /// </summary>
        private int _valueColumn = 1;
        public int ValueColumn
        {
            get
            {
                return _valueColumn;
            }

            private set
            {
                _valueColumn = value > 0 ? value : 0;
            }
        }

        private string _sheetName = null;
        public string SheetName
        {
            get
            {
                if (_sheetName == null)
                {
                    FileInfo fi = new FileInfo(this.Path);
                    _sheetName = fi.Extension;
                }
                return _sheetName;
            }

            set    
            {
                _sheetName = value;
            }
        }

#endregion
       
#region Constructor

        /// <summary>
        /// 생성자
        /// </summary>
        public XlsFile()
        {

        }

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="path">경로</param>
        public XlsFile(string path)           
        {
            this.Path = path;
        }

#endregion

#region Private Functions      


#endregion
        
#region Protected Functions 

        /// <summary>
        /// 헤더쓰기
        /// </summary>
        /// <param name="sheet">데이터를 쓸 시트</param>
        protected virtual void WriteHeader(HSSFSheet sheet)
        {            
            sheet.Cell(0, this.IdColumn).SetCellValue("ID");
            sheet.Cell(0, this.ValueColumn).SetCellValue("Value");
        }

        /// <summary>
        /// 내용쓰기
        /// </summary>
        /// <param name="sheet">데이터를 쓸 시트</param>
        protected virtual void WriteContent(HSSFSheet sheet)
        {
            int row = 1;
            foreach (var item in this.Data)
            {
                sheet.Cell(row, this.IdColumn).SetCellValue(item.Key);
                sheet.Cell(row, this.ValueColumn).SetCellValue(item.Value);
                ++row;
            }
        }

        /// <summary>
        /// 내용 읽기
        /// </summary>
        /// <param name="collection">데이터를 쓸 컬렉션</param>
        /// <param name="sheet">데이터를 읽어들일 시트</param>
        protected virtual void ReadXls(Dictionary<string, string> collection, HSSFSheet sheet)
        { 
            int startRow = this.StartRow;
            int totalRows = sheet.LastRowNum;
            for (int rowIndex = startRow; rowIndex < totalRows; rowIndex++)
            {
                try
                {
                    HSSFCell idCell = sheet.Cell(rowIndex, this.IdColumn);
                    HSSFCell valueCell = sheet.Cell(rowIndex, this.ValueColumn);

                    string id = idCell.ToString().Trim();
                    string value = valueCell.ToString().Trim();

                    collection.Add(id, value);
                }
                catch (System.Exception ex)
                {
                    this.OnError(ex);
                }
            }
        }
        
        /// <summary>
        /// 엑셀파일로부터 데이터 로드
        /// </summary>
        /// <param name="path">경로</param>
        /// <returns>엑셀파일에서 추출한 리소스 모음</returns>
        protected override Dictionary<string, string> LoadData(string path)
        {
            Dictionary<string, string> collection = new Dictionary<string, string>();

            try
            {
                //엑셀 파일을 헤더줄을 제외하고 읽어들임 
                FileInfo fi = new FileInfo(path);
                using (System.IO.FileStream stream = fi.OpenRead())
                {
                    HSSFWorkbook importFile = new HSSFWorkbook(stream);
                    HSSFSheet sheet = importFile.GetSheetAt(this.SheetNo);

                    this.ReadXls(collection, sheet);            
                }             
            }
            catch (System.Exception ex)
            {
                this.OnError(ex);
            }

            return collection;
        }

        /// <summary>
        /// 엑셀파일에 데이터 저장
        /// </summary>
        /// <param name="path">저장</param>
        /// <returns></returns>
        protected override bool SaveData(string path)
        {
            try
            {
                FileInfo newFile = new FileInfo(path);
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    HSSFWorkbook workbook = new HSSFWorkbook();

                    //시트 제목 지정 
                    string worksheetTitle = this.SheetName;
                    HSSFSheet sheet = workbook.CreateSheet(worksheetTitle);
                    
                    //헤더입력
                    this.WriteHeader(sheet);

                    //내용 채우기 
                    this.WriteContent(sheet);                  

                    workbook.Write(fs);
                }
            }
            catch (System.Exception ex)
            {
                this.OnError(ex);
            }

            return true;
        }

        /// <summary>
        /// 확장자 검사, 확장자가 xls 인지 검사함
        /// </summary>
        /// <param name="path">파일경로</param>
        /// <returns>확장자가 xls인지 아닌지 여부 반환</returns>
        protected override bool IsCorrectExtension(string path)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            return fi.Extension.Equals(".xls", StringComparison.InvariantCultureIgnoreCase);
        }
               

#endregion
        

    }
}
